import { Layout, Menu, Space, Row, Col, message, Statistic } from "antd";
import { QuestionCircleOutlined, LogoutOutlined } from "@ant-design/icons";
import { MenuProps } from "antd/lib";
import { getCookie, removeCookie, setCookie } from "@utils/StorageUtil";
import { useNavigate } from "react-router-dom";
import type { CountdownProps } from "antd";
import { useEffect, useState } from "react";
import TraninProblemProblem from "./TrainProblemProblem";
import TrainProblemType from "./TrainProblemType";
import { httpPost } from "@utils/HttpUtil";

const { Countdown } = Statistic;

const { Header, Content } = Layout;

function TrainProblem() {
  const navigate = useNavigate();

  // 导航菜单项
  const navItems = [
    { label: "反馈", key: "feedback" },
    {
      label: (
        <>
          <LogoutOutlined />
          退出
        </>
      ),
      key: "logout",
      style: { marginLeft: 20 },
    },
  ];

  const problemItem = httpPost("/userTrain/study", {
    type: "knowledge",
  }).data;
  setCookie("knowledgeId", '' + problemItem.knowledgeId);
  setCookie("startTrainTime", (Date.now()) + "");

  //常用参数
  const maxTrainTime = 1000 * 600; // 最长学习时间：10分钟
  const minTrainTime = 10; // 最短学习时间(单位：秒)
  const [trainItem, setTrainItem] = useState(problemItem);
  var trainTime = Date.now() + maxTrainTime; // 设置初始倒计时为10分钟后
  setCookie("trainTime", trainTime+"");
  const [deadline, setDeadline] = useState(trainTime);

  // 提交训练结果
  const submitTrain = (trainType: any, trainId: any, result: any, costTime: number) => {
    httpPost("/userTrain/submitTrain", {
      trainType: trainType,
      trainId: trainId,
      result: result,
      costTime: costTime,
    });
  };

  // 获取一个新的训练项
  const refreshTrain = (type: string) => {

    //目前仅实现了知识点，以下全部为训练知识点的逻辑
    if(type !== "knowledge") return;

    //获取当前知识点id
    var knowledgeId = getCookie("knowledgeId");
    var startTrainTime = getCookie("startTrainTime");
    var now = Date.now();
    // 计算本次训练的耗时，单位为秒
    var costTime = Number.parseInt((now - parseInt(startTrainTime)) / 1000+"");

    // 计算上次训练的时间,如果太短不允许更换训练内容
    if (costTime < minTrainTime) {
      message.warning("太快了, 学习" + minTrainTime + "秒后可进行下一次学习");
      return;
    }
    
    //提交本次训练内容
    submitTrain("knowledge", knowledgeId, "success", costTime);

    // 调用接口获取新的训练内容
    var train = httpPost("/userTrain/study", {
      type: type,
    }).data;
    setTrainItem(train);

    //设置新的知识点id
    setCookie("knowledgeId", '' + train.knowledgeId);
    setCookie("startTrainTime", (Date.now()) + "");

    // 重置倒计时为10分钟后
    var resetTime = Date.now() + maxTrainTime;
    setDeadline(resetTime);
    setCookie("trainTime", resetTime+"");
  };

  

  const onFinish: CountdownProps["onFinish"] = () => {
    if (trainItem.type === "knowledge") {
      // 如果是知识点类型，直接提交并刷新
      refreshTrain("knowledge");
    }
    message.info("时间到，系统已自动提交");
  };

  const onClick: MenuProps["onClick"] = (e) => {
    var id = e.key;
    switch (id) {
      case "feedback":
        console.log("feedback");
        message.info("反馈成功，系统会尽快处理");
        break;
      case "logout":
        removeCookie("train");
        removeCookie("problemTrain");
        navigate("/study");
        break;
      default:
        break;
    }
  };

  

  useEffect(() => {
    const handleKeyDown = (event: any) => {
      if (event.key === "ArrowDown") {
        refreshTrain("knowledge");
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, []);

  return (
    <Layout style={{ background: "white" }}>
      <Header
        style={{
          background: "white",
          borderBottom: "1px solid #f0f0f0",
          padding: "0 24px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        {trainItem.status !== "completed" ? (
          <div style={{ color: "rgba(0,0,0,0.85)", fontSize: 16 }}>
            <QuestionCircleOutlined style={{ marginRight: 8 }} />
            {trainItem.knowledgeName}
          </div>
        ) : (
          <div style={{ color: "rgba(0,0,0)", fontSize: 16 }}></div>
        )}
        {trainItem.status !== "completed" ? (
          <Countdown
            value={deadline}
            format="mm:ss"
            prefix="限时:"
            valueStyle={{ color: "#ec2c64" }}
            onFinish={onFinish}
            style={{ fontSize: 24, fontWeight: "bold" }}
          />
        ) : (
          <></>
        )}
        <Space>
          <Menu
            mode="horizontal"
            items={navItems}
            onClick={onClick}
            style={{ border: "none", background: "transparent" }}
          />
        </Space>
      </Header>

      {/* 题目内容区域 */}
      {trainItem.status === "completed" ? (
        <Layout style={{ background: "white" }}>
          <Content
            style={{ padding: "240px 24px", width: "90%", margin: "0 auto" }}
          >
            <Row gutter={[24, 24]}>
              <Col span={24}>
                <div
                  style={{
                    textAlign: "center",
                    fontSize: 24,
                    color: "#52c41a",
                  }}
                >
                  恭喜你，本章节所有题目已完成！请切换到下一个章节或者等明天再来哦！
                </div>
              </Col>
            </Row>
          </Content>
        </Layout>
      ) : (
        <Content
          style={{ padding: "40px 24px", width: "90%", margin: "0 auto" }}
        >
          <Row gutter={[24, 24]}>
            <Col xs={24} md={12}>
              <TraninProblemProblem trainItem={trainItem} />
            </Col>
            <Col xs={24} md={12}>
              <TrainProblemType
                trainItem={trainItem}
                refreshTrain={refreshTrain}
              />
            </Col>
          </Row>
        </Content>
      )}
    </Layout>
  );
}

export default TrainProblem;
